//
//  DrawingView.m
//  etionUI
//
//  Created by wangjian on 5/14/13.
//
//

#import "DrawingView.h"
#import "ExtendSelector.h"
#import "CircleButton.h"
#import "UserGuideManager.h"
#import "UserGuideView.h"

#pragma mark -
#define BTN_SIZE 32
#define BTN_BORDER_DISTANCE 15
//---------------------------------------------------------------------
// Drawing Tools

CGPoint midPoint(CGPoint p1, CGPoint p2)
{
    return CGPointMake((p1.x + p2.x) * 0.5, (p1.y + p2.y) * 0.5);
}

@implementation CDrawingTool

@synthesize m_toolColor, m_toolWidth, m_startPoint, m_endPoint, m_blendMode;

- (id)init
{
    self = [super init];
    if (self != nil) {
        self.lineCapStyle = kCGLineCapRound;
        m_blendMode = kCGBlendModeNormal;
    }
    return self;
}

- (void)setInitialPoint:(CGPoint)firstPoint
{
    [self moveToPoint:firstPoint];
}

- (void)moveFromPoint:(CGPoint)startPoint toPoint:(CGPoint)endPoint
{
    [self addQuadCurveToPoint:midPoint(endPoint, startPoint) controlPoint:startPoint];
}

- (void)draw
{
    
}

- (void)dealloc
{
    [m_toolColor release];
    [super dealloc];
}

@end

@implementation CDrawingToolPen

- (void)draw
{
    [m_toolColor setStroke];
    [self strokeWithBlendMode:m_blendMode alpha:1.0];
}

@end

@implementation CDrawingToolBrush
{
//    CGGradientRef m_gradient;
}

//- (void)setM_toolColor:(UIColor *)toolColor
//{
//    UIColor *tmpColor = [toolColor retain];
//    [m_toolColor release];
//    m_toolColor = tmpColor;
//    
//    UIColor *color1 = [UIColor colorWithRed:1.0 green:0 blue:0 alpha:0];
//    UIColor *color2 = [UIColor colorWithRed:1.0 green:0 blue:0 alpha:1];
//    CFArrayRef colorArray = CFArrayCreate(kCFAllocatorDefault, (const void*[]){color1.CGColor, color2.CGColor, color1.CGColor}, 3, nil);
//    m_gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), colorArray, (CGFloat[]){0.0f, 0.5f,1.0f});
//}

- (void)moveFromPoint:(CGPoint)startPoint toPoint:(CGPoint)endPoint
{
    m_startPoint = startPoint, m_endPoint = endPoint;
    [self addQuadCurveToPoint:midPoint(endPoint, startPoint) controlPoint:startPoint];
}

- (void)draw
{
    [m_toolColor setStroke];
    [self strokeWithBlendMode:m_blendMode alpha:1.0];
}

@end

@implementation CDrawingToolFog


@end

//---------------------------------------------------------------------
// Drawing View

#pragma mark -

@implementation CDrawingView
{
    CDrawingToolPen *pen;
    CDrawingToolBrush *brush;
    CDrawingToolFog *fog;
    
    CDrawingTool *curTool;
    BOOL beginDrawing;
}

@synthesize m_toolColor, m_toolWidth, m_bEraser, m_drawingToolType, m_image;

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        self.backgroundColor = [UIColor clearColor];
        self.m_toolColor = [UIColor redColor];
        m_toolWidth = 10;
        self.m_drawingToolType = EDrawingToolTypeBrush;
    }
    return self;
}

- (void)dealloc
{
    [pen release];
    [brush release];
    [fog release];
    [m_toolColor release];
    [m_image release];
    [super dealloc];
}

- (void)drawRect:(CGRect)rect
{
    [m_image drawInRect:self.bounds];
    [curTool draw];
}

- (void)updateCacheImage
{
    // store the image
    UIGraphicsBeginImageContext(self.bounds.size);
    
    [m_image drawAtPoint:CGPointZero];
    [curTool draw];
    
    [m_image release];
    m_image = [UIGraphicsGetImageFromCurrentImageContext() retain];
    UIGraphicsEndImageContext();
}

- (void)setM_drawingToolType:(EDrawingToolType)drawingToolType
{
    m_drawingToolType = drawingToolType;
    switch (drawingToolType)
    {
        case EDrawingToolTypePen:
            if (pen == nil)
            {
                pen = [[CDrawingToolPen alloc] init];
            }
            curTool = pen;
            break;
        case EDrawingToolTypeBrush:
            if (brush == nil)
            {
                brush = [[CDrawingToolBrush alloc] init];
            }
            curTool = brush;
            break;
        case EDrawingToolTypeFog:
            if (fog == nil)
            {
                fog = [[CDrawingToolFog alloc] init];
            }
            curTool = fog;
            break;
        default:
            break;
    }
    curTool.lineWidth = m_toolWidth;
    curTool.m_toolColor = m_toolColor;
}

- (void)setM_toolColor:(UIColor *)toolColor
{
    UIColor *tmpColor = [toolColor retain];
    [m_toolColor release];
    m_toolColor = tmpColor;
    
    curTool.m_toolColor = toolColor;
}

- (void)setM_toolWidth:(CGFloat)toolWidth
{
    m_toolWidth = toolWidth;
    curTool.lineWidth = toolWidth;
}

- (void)setM_bEraser:(BOOL)bEraser
{
    if (bEraser == YES)
    {
        curTool.m_blendMode = kCGBlendModeClear;
    }
    else
    {
        curTool.m_blendMode = kCGBlendModeNormal;
    }
}

#pragma mark Touch Methods

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    beginDrawing = YES;
    if ([self.delegate respondsToSelector:@selector(drawingViewShouldBeginDrawing:)])
    {
        beginDrawing = [self.delegate drawingViewShouldBeginDrawing:self];
    }
    if (beginDrawing == YES)
    {
        UITouch *touch = [touches anyObject];
        [curTool moveToPoint:[touch locationInView:self]];
        if ([self.delegate respondsToSelector:@selector(drawingViewDidBeginDrawing:)])
        {
            [self.delegate drawingViewDidBeginDrawing:self];
        }
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (beginDrawing == YES)
    {
        UITouch *touch = [touches anyObject];
        [curTool moveFromPoint:[touch previousLocationInView:self] toPoint:[touch locationInView:self]];
        [self setNeedsDisplay];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (beginDrawing == YES)
    {
        [self touchesMoved:touches withEvent:event];
        [self updateCacheImage];
        [curTool removeAllPoints];
        
        if ([self.delegate respondsToSelector:@selector(drawingViewDidEndDrawing:)])
        {
            [self.delegate drawingViewDidEndDrawing:self];
        }
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesEnded:touches withEvent:event];
}

@end

@interface CDrawingBoardView() <CDrawingViewDelegate>

@end

@implementation CDrawingBoardView
{
    CCircleButton *_cancelBtn;
    CCircleButton *_saveBtn;
    CExtendItemSelector *_toolSelector;
    CExtendColorSelector *_colorSelector;
}

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        _drawingView = [[[CDrawingView alloc] initWithFrame:self.bounds] autorelease];
        _drawingView.delegate = self;
        [self addSubview:_drawingView];
        
        _cancelBtn = [[[CCircleButton alloc] initWithFrame:CGRectMake(-BTN_SIZE, BTN_BORDER_DISTANCE, BTN_SIZE, BTN_SIZE) normalImage:[UIImage imageNamed:@"pb_backarrow_normal"] highlightedImage:[UIImage imageNamed:@"pb_backarrow_selected"]] autorelease];
        [_cancelBtn addTarget:self action:@selector(cancelEdit) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_cancelBtn];
        
        _saveBtn = [[[CCircleButton alloc] initWithFrame:CGRectMake(self.width, BTN_BORDER_DISTANCE, BTN_SIZE, BTN_SIZE) normalImage:[UIImage imageNamed:@"pb_save_normal"] highlightedImage:[UIImage imageNamed:@"pb_save_selected"]] autorelease];
        [_saveBtn addTarget:self action:@selector(saveEdit) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_saveBtn];
        
        _colorSelector = [[[CExtendColorSelector alloc] initWithFrame:CGRectMake(-BTN_SIZE, self.height-BTN_SIZE-BTN_BORDER_DISTANCE, BTN_SIZE, BTN_SIZE)] autorelease];
        _colorSelector.arColors = [NSArray arrayWithObjects:[UIColor colorWithHex:0xE74C3C], [UIColor colorWithHex:0xE67E22], [UIColor colorWithHex:0xF1C40F], [UIColor colorWithHex:0x2ECC71], [UIColor colorWithHex:0x3498DB], [UIColor colorWithHex:0x9B59B6], [UIColor colorWithHex:0x2C3E50], [UIColor whiteColor], nil];
        _colorSelector.arWidths = [NSArray arrayWithObjects:[NSNumber numberWithFloat:3.0], [NSNumber numberWithFloat:5.0], [NSNumber numberWithFloat:10.0], [NSNumber numberWithFloat:15.0], nil];
        [_colorSelector addTarget:self action:@selector(colorSelectorValueChange:) forControlEvents:UIControlEventValueChanged];
        [_colorSelector addTarget:self action:@selector(colorSelectorClicked:) forControlEvents:UIControlEventTouchUpInside];
        _colorSelector.curWidthIndex = 1;
        _colorSelector.curColorIndex = 4;
        [self addSubview:_colorSelector];
        
        _toolSelector = [[[CExtendItemSelector alloc] initWithFrame:CGRectMake(self.width, self.height-BTN_SIZE-BTN_BORDER_DISTANCE, BTN_SIZE, BTN_SIZE) normalImages:[NSArray arrayWithObjects:[UIImage imageNamed:@"pb_pen_normal"], [UIImage imageNamed:@"pb_erase_normal"], nil] highlightedImages:[NSArray arrayWithObjects:[UIImage imageNamed:@"pb_pen_selected"], [UIImage imageNamed:@"pb_erase_selected"], nil] titles:[NSArray arrayWithObjects:@"画笔", @"橡皮擦", nil]] autorelease];
        _toolSelector.extendDir = EExtendSelectorDirUp;
        [_toolSelector addTarget:self action:@selector(toolSelectorValueChange:) forControlEvents:UIControlEventValueChanged];
        [_toolSelector addTarget:self action:@selector(toolSelectorClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_toolSelector];
        
        self.drawingFrame = self.bounds;
        self.drawingView.m_toolColor = _colorSelector.curColor;
        self.drawingView.m_toolWidth = _colorSelector.curWidth;
        
        [self showButtonsAnimated:YES complete:^(BOOL finished) {
            if ([CUserGuideManager userGuideStatusForKey:@"DrawingView"] == EUserGuideStatusNeverDisplay)
            {
                CUserGuideUnit *unitBack = [CUserGuideUnit unitWithType:EUserGuideUnitTypeCircleNode area:_cancelBtn.frame text:@"点击这里返回，取消您的涂鸦" image:nil];
                CUserGuideUnit *unitSave = [CUserGuideUnit unitWithType:EUserGuideUnitTypeCircleNode area:_saveBtn.frame text:@"点击这里保存您的涂鸦" image:nil];
                CUserGuideUnit *unitColor = [CUserGuideUnit unitWithType:EUserGuideUnitTypeCircleNode area:_colorSelector.frame text:@"点击此处可以选择画笔颜色和尺寸" image:nil];
                CUserGuideUnit *unitTool = [CUserGuideUnit unitWithType:EUserGuideUnitTypeCircleNode area:_toolSelector.frame text:@"点击此处可以选择画笔或者橡皮擦" image:nil];
                [[CUserGuideView userGuideViewWithUnits:[NSArray arrayWithObjects:unitBack, unitSave, unitColor, unitTool, nil] delegate:nil] show];
                [CUserGuideManager setUserGuideStatus:EUserGuideStatusHasDisplay forKey:@"DrawingView"];
            }
        }];
    }
    return self;
}

- (void)setDrawingFrame:(CGRect)drawingFrame
{
    _drawingFrame = drawingFrame;
    self.drawingView.frame = drawingFrame;
}

- (void)showButtonsAnimated:(BOOL)animated complete:(void (^)(BOOL finished))complete
{
    [UIView animateWithDuration:animated?.25:0.0 animations:^{
        _cancelBtn.left = BTN_BORDER_DISTANCE;
        _saveBtn.right = self.width - BTN_BORDER_DISTANCE;
        _toolSelector.right = self.width - BTN_BORDER_DISTANCE;
        _colorSelector.left = BTN_BORDER_DISTANCE;
    } completion:^(BOOL finished) {
        complete(finished);
    }];
}

- (void)hideButtonsAnimated:(BOOL)animated complete:(void (^)(BOOL finished))complete
{
    [UIView animateWithDuration:animated?.25:0.0 animations:^{
        _cancelBtn.right = 0;
        _saveBtn.left = self.width;
        _toolSelector.left = self.width;
        _colorSelector.right = 0;
    } completion:^(BOOL finished) {
        complete(finished);
    }];
}

- (void)cancelEdit
{
    [_toolSelector shrink];
    [_colorSelector shrink];
    [UIView animateWithDuration:.25 animations:^{
        self.drawingView.alpha = 0.0;
    }];
    [self.delegate drawingBoardViewCancelEdit:self];
}

- (void)saveEdit
{
    [_toolSelector shrink];
    [_colorSelector shrink];
    [self.delegate drawingBoardViewFinishedEdit:self];
}

- (void)colorSelectorValueChange:(CExtendColorSelector *)selector
{
    self.drawingView.m_toolColor = [_colorSelector.arColors objectAtIndex:_colorSelector.curColorIndex];
    self.drawingView.m_toolWidth = [[_colorSelector.arWidths objectAtIndex:_colorSelector.curWidthIndex] floatValue];
}

- (void)toolSelectorValueChange:(CExtendItemSelector *)selector
{
    if (selector.curSelectedIndex == 1)
    {
        self.drawingView.m_toolColor = [UIColor clearColor];
        self.drawingView.m_toolWidth = 30;
        self.drawingView.m_bEraser = YES;
        [UIView animateWithDuration:.25 animations:^{
            _colorSelector.alpha = 0.0;
        } completion:^(BOOL finished) {
            _colorSelector.hidden = YES;
        }];
    }
    else
    {
        self.drawingView.m_toolColor = [_colorSelector.arColors objectAtIndex:_colorSelector.curColorIndex];
        self.drawingView.m_toolWidth = [[_colorSelector.arWidths objectAtIndex:_colorSelector.curWidthIndex] floatValue];
        self.drawingView.m_bEraser = NO;
        _colorSelector.hidden = NO;
        [UIView animateWithDuration:.25 animations:^{
            _colorSelector.alpha = 1.0;
        } completion:^(BOOL finished) {
        }];
    }
}

- (void)colorSelectorClicked:(CExtendColorSelector *)selector
{
    [_toolSelector shrink];
}

- (void)toolSelectorClicked:(CExtendItemSelector *)selector
{
    [_colorSelector shrink];
}

- (BOOL)drawingViewShouldBeginDrawing:(CDrawingView *)view
{
    if (_toolSelector.bIsExtend == YES || _colorSelector.bIsExtend == YES)
    {
        [_toolSelector shrink];
        [_colorSelector shrink];
        return NO;
    }
    return YES;
}

@end
